<?php

declare(strict_types=1);

namespace App\Service;

use AlibabaCloud\Client\AlibabaCloud;
use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Utils\CustomUtils;
use App\Utils\GoogleAuthenticator;

//* 通用service
class CommonService
{

    /**
     * @return string
     * 生成google密钥
     */
    public function generateGoogleAuthSecret() {
        $googleAuthenticator = new GoogleAuthenticator();
        return $googleAuthenticator->createSecret();
    }
    
    /**
     * @param $secret
     * @param $code
     * @return array
     * google验证码校验
     */
    public function checkGoogleCode($secret, $code) {
        $googleAuthenticator = new GoogleAuthenticator();
        $checkResult = $googleAuthenticator->verifyCode($secret, $code);
        if (!$checkResult) {
            throw new XZXValidationException("google 验证码验证失败");
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),CustomUtils::xzxEmptyObject());
    }

    /**
     * @return array
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     * 阿里云oss临时凭证
     */
    public function aliOssTmpKey() {
        //构建一个阿里云客户端，用于发起请求。
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        $accessKeyId = config('aliOssAccessKeyId');
        $accessSecret = config('aliOssAccessSecret');
        $regionId = config('aliOssRegionId');
        $roleArn = config('aliOssRoleArn');
        $roleSessionName = config('aliOssRoleSessionName');
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        $result = AlibabaCloud::rpc()
            ->product('Sts')
            ->scheme('https') // https | http
            ->version('2015-04-01')
            ->action('AssumeRole')
            ->method('POST')
            ->host('sts.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => $regionId,
                    'RoleArn' => $roleArn,
                    'RoleSessionName' => $roleSessionName,
                ],
            ])
            ->request()->toArray();
        $result['Bucket'] = config('aliOssBucket');
        $result['Region'] = config('aliOssRegionId');

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $result);
    }
}